/*momo314*/

//check browser support <audio> or not
var AudioTest = document.createElement('audio');
var BroswerSupportAudio = false;
if (AudioTest.play)
    BroswerSupportAudio = true;
if (BroswerSupportAudio) {
    //    var IsBrowserIE = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
    //    if (IsBrowserIE) {
    //        var userAgent = window.navigator.userAgent.toLowerCase();
    //        $.browser.msie10 = $.browser.msie && /msie 10\.0/i.test(userAgent);
    //        $.browser.msie9 = $.browser.msie && /msie 9\.0/i.test(userAgent);
    //        $.browser.msie8 = $.browser.msie && /msie 8\.0/i.test(userAgent);
    //        $.browser.msie7 = $.browser.msie && /msie 7\.0/i.test(userAgent);
    //        $.browser.msie6 = !$.browser.msie8 && !$.browser.msie7 && $.browser.msie && /msie 6\.0/i.test(userAgent);
    //        if ($.browser.msie9 || $.browser.msie8 || $.browser.msie7 || $.browser.msie6)
    //            BroswerSupportAudio = false;
    //    }
    //    else {
    if (AudioTest.canPlayType('audio/mp3') == '') {
        BroswerSupportAudio = false;
    }
    //    }
}

//BroswerSupportAudio = false;

//if support <audio>, load jquery-ui.js for slider
if (BroswerSupportAudio)
    document.write('<script type="text/javascript" src="' + window.location.protocol + '//autocall.bitauto.com/pcl/scripts/jquery-ui.js"></script>');

//interface address for calllog identity type
var InterfaceUrl = {
    '1': window.location.protocol + '//autocall.bitauto.com/PCL/RecordSoundData.ashx',//使用商机ID
    '2': window.location.protocol + '//autocall.bitauto.com/PCL/AutoCallCenterRecord.ashx',//使用呼叫中心ID
    '3': window.location.protocol + '//autocall.bitauto.com/epbox/RecordSoundData.ashx',//使用盒子ID
    '4': window.location.protocol + '//autocall.bitauto.com/PCL/UrlRecord.ashx'//使用拼接好的录音文件地址
};


/*********************** <Audio> Player [NEW] **************************/
//audio control
var recorder = null;
//audio logic
function AudioRecorder(param/*{ InterfaceUrl: '', RecordID: '' }*/) {
    var Html = '\
<div id="audiopassword" class="bd haskey" style="display: none;">\
    请输入收听密码\
    <div class="input_search">\
        <input type="password" id="txt4password" class="text fl" name="" /><a href="javascript:;" class="btn btnsubmit fl"><input type="button" id="btn4password" value="确定" /></a>\
    </div>\
</div>\
<div id="audioplayer" class="bd audio" style="display:none;">\
    <a href="javascript:;" class="close">关闭</a>\
    <div class="audio_module">\
        <span id="audiotime" class="time fr">00:00</span>\
        <a id="audiocontroller" href="javascript:;" class="icon icon_play fl"></a>\
        <div id="process" class="ui-slider ui-slider-horizontal ui-widget ui-widget-content ui-corner-all fl" aria-disabled="false">\
            <a id="processcontroller" class="ui-slider-handle ui-state-default ui-corner-all" href="#" style="left: 0%;"></a>\
        </div>\
    </div>\
    <audio id="audio" draggable="true"></audio>\
    <input type="hidden" id="audiopause" value="0" />\
</div>\
<div id="audiomessage" class="bd error_tip" style="display: none;">\
    <span id="audiomessagecontent"></span> <a href="javascript:;" class="btn btnsubmit">\
        <input type="button" id="btn4message" value="确定" /></a>\
</div>';

    $('#DivDialog').empty();
    $('#DivDialog').append(Html);

    //关闭
    $('#DivDialog .close').unbind('click');
    $('#DivDialog .close').bind('click', function () {
        recorder.CloseFrame();
    });

    this.IsPlaying = false;
    this.PauseCount = 0;
    this.PlayInterval = null; //已废弃，改为使用AudioRecorder.PlayInterval
    this.AudioUrl = '';
    this.InterfaceUrl = InterfaceUrl[String(param.InterfaceID || '1')];
    this.RecordID = encodeURIComponent(param.RecordID || '');
    this.IsDragging = false;
    this.DraggingStartPoint = undefined;
    this.DraggingEndPoint = undefined;
    this.DraggingInterval = null;
    this.AnimateIsEnded = true;
    this.AnimateIsStoped = true;
    this.LastCurrentTime = -1;
    this.LastCurrentShowTime = -1;
    var Password = '';
    var AudioError = {
        "0": "成功",
        "1": "无法验证录音归属",
        "2": "你输入的收听密码不正确，请重试。"/*"无法验证收听权限"*/,
        "3": "无法获取该录音文件，请稍后再试。"/*"无法获取录音文件"*/,
        "4": "无法验证收听密码"
    };


    //播放
    this.Play = function () {
        var audio = $('#audio')[0];
        audio.src = this.AudioUrl;
        $(audio)[0].onplaying = function () {
            if (recorder) {
                recorder.IsPlaying = true;
            }
        };
        $(audio)[0].onpause = function () {
            if (recorder) {
                recorder.IsPlaying = false;
            }
        };
        $(audio)[0].onended = function () {
            if (recorder) {
                recorder.IsPlaying = false;
            }
        };
        if ($.Tools.IsPCBrowser()) {
            $('#audiocontroller').removeClass('icon_play');
            $('#audiocontroller').addClass('icon_pause');
            this.AnimateIsEnded = false;
            audio.play();
            recorder.IsPlaying = true;
            Process();
        } else {
            $('#audiocontroller').removeClass('icon_pause');
            $('#audiocontroller').addClass('icon_play');
            this.AnimateIsEnded = true;
            recorder.IsPlaying = false;
            $('#audiocontroller').unbind('click');
            $('#audiocontroller').unbind('click.ForMobile');
            $('#audiocontroller').bind('click.ForMobile', function () {
                if (recorder.IsPlaying) {
                    recorder.Pause();
                }
                else {
                    if (recorder.PauseCount > 0) {
                        recorder.Continue();
                    }
                    else {
                        audio.play();
                        recorder.IsPlaying = true;
                        Process();
                    }
                }
            });
        }
    };

    //暂停
    this.Pause = function () {
        var audio = $('#audio')[0];
        $("#audiopause").val(audio.currentTime);
        audio.pause();
        $('#audiocontroller').removeClass('icon_pause');
        $('#audiocontroller').addClass('icon_play');
        this.IsPlaying = false;
        this.AnimateIsStoped = true;
        this.PauseCount++;
        clearInterval(AudioRecorder.PlayInterval);
        $('#processcontroller').stop(true, false);
        recorder.AnimateIsStoped = true;
    };

    //继续播放事件
    this.Continue = function () {
        var audio = $('#audio')[0];
        audio.startTime = $("#audiopause").val();
        audio.play();
        $('#audiocontroller').removeClass('icon_play');
        $('#audiocontroller').addClass('icon_pause');
        this.IsPlaying = true;
        $('#processcontroller').animate({ left: '100%' }, (Duration() - audio.currentTime) * 1000, 'linear', function () {
            $('#processcontroller').stop(true, false);
            $('#processcontroller').css('left', '0%');
            recorder.AnimateIsEnded = true;
            recorder.AnimateIsStoped = true;
        });
        this.AnimateIsStoped = false;
    };

    //重置播放事件
    this.Reset = function () {
        var audio = $('#audio')[0];
        $('#audiocontroller').removeClass('icon_pause').removeClass('icon_play').addClass('icon_play');
        if (!this.IsPlaying) {
            if (this.PauseCount > 0)
                this.Continue();
            else
                this.Play();
        }
        recorder.ProcessTo(0);
        recorder.Pause();
        clearInterval(AudioRecorder.PlayInterval);
        recorder.PlayInterval = null;
        recorder.IsPlaying = false;
        recorder.AnimateIsEnded = false;
        recorder.AnimateIsStoped = false;
        recorder.PauseCount = 0;
    };

    //播放进度条的转变事件
    this.ProcessTo = function (percent) {
        var audio = $('#audio')[0];
        var currenttime = percent * Duration();
        try {
            $.Tools.Log('播放进度条定位函数 设置定位时间 ' + currenttime + " 准备设置");
            audio.pause();
            audio.currentTime = currenttime;
            audio.play();
            $.Tools.Log('播放进度条定位函数 设置定位时间 ' + currenttime + " 设置完成");
        }
        catch (e) {
            var ProcessMessage = '设置播放时间失败\r\n异常信息：' + e.Message + "\r\n异常描述：" + e.Description;
            $.Tools.Log(ProcessMessage);
            //alert(ProcessMessage);
        }
        $("#processcontroller").css('left', String(percent * 100) + '%');
        audio.play();
        Process();
    };

    //显示界面
    this.ShowFrame = function () {
        var xhr = new XMLHttpRequest();
        if ("withCredentials" in xhr) {
            //支持CORS
            $.ajax({
                type: 'post',
                xhrFields: {
                    withCredentials: true
                },
                dataType: 'json',
                url: recorder.InterfaceUrl + '?RecordID=' + recorder.RecordID + '&OnlyFlag=1&FlagType=json',
                success: function (data, textStatus) {
                    if (data && data.Error) {
                        switch (data.Error) {
                            case 0:
                                if (recorder != null)
                                    recorder.AudioUrl = recorder.InterfaceUrl + '?RecordID=' + recorder.RecordID;
                                break;
                            default:
                                if (recorder != null)
                                    recorder.AudioUrl = '';
                                break;
                        }
                    }
                    else {
                        if (recorder != null && recorder.AudioUrl != null)
                            recorder.AudioUrl = recorder.InterfaceUrl + '?RecordID=' + recorder.RecordID;
                    }
                    if (recorder.AudioUrl != '')
                        recorder.ShowPlayerFrame();
                    else {
                        if (data.Error == 4)
                            recorder.ShowPasswordFrame();
                        else
                            recorder.ShowMessageFrame(AudioError[String(data.Error)]);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    recorder.ShowMessageFrame(AudioError['3']);
                }
            });
        }
            /*else if (typeof XDomainRequest != "undefined") {
                //不支持CORS => IE8/IE9
                //但XDomainRequest 不支持携带Cookie，所以与jsonp没有什么区别
            }*/
        else {
            //不支持CORS => lte IE8
            $.ajax({
                type: 'get',
                dataType: 'jsonp',
                jsonp: 'CALLBACK',
                url: recorder.InterfaceUrl + '?RecordID=' + recorder.RecordID + '&OnlyFlag=1&FlagType=jsonp',
                success: function (data, textStatus) {
                    if (data && data.Error) {
                        switch (data.Error) {
                            case 0:
                                if (recorder != null)
                                    recorder.AudioUrl = recorder.InterfaceUrl + '?RecordID=' + recorder.RecordID;
                                break;
                            default:
                                if (recorder != null)
                                    recorder.AudioUrl = '';
                                break;
                        }
                    }
                    else {
                        if (recorder != null && recorder.AudioUrl != null)
                            recorder.AudioUrl = recorder.InterfaceUrl + '?RecordID=' + recorder.RecordID;
                    }
                    if (recorder.AudioUrl != '')
                        recorder.ShowPlayerFrame();
                    else {
                        if (data.Error == 4)
                            recorder.ShowPasswordFrame();
                        else
                            recorder.ShowMessageFrame(AudioError[String(data.Error)]);
                    }
                },
                error: function () {
                    recorder.ShowMessageFrame(AudioError['3']);
                }
            });
        }
    };

    //关闭界面
    this.CloseFrame = function () {
        if (recorder && recorder != null && recorder.IsPlaying) {
            recorder.Reset();
        }
        clearInterval(AudioRecorder.PlayInterval);
        AudioRecorder.PlayInterval = null;
        recorder = null;
        $('#DivDialog').hide();
        $('#DivDialog').empty();
        $('#DivDialog').html('');
        $('#CurrentAudioTrigger').removeAttr('clicked');
        $('*[clicked="clicked"]').removeAttr('clicked');
        $(document).unbind('mouseup.dragging');
    };

    //显示密码界面
    this.ShowPasswordFrame = function () {
        $('#audioplayer').css('display', 'none');
        $('#audiomessage').css('display', 'none');
        $('#audiopassword').css('display', '');

        $('#btn4password').unbind('click');
        $('#btn4password').bind('click', function () {
            var psw = $('#txt4password').val();
            var xhr = new XMLHttpRequest();
            if ("withCredentials" in xhr) {
                //支持CORS
                $.ajax({
                    type: 'post',
                    xhrFields: {
                        withCredentials: true
                    },
                    dataType: 'json',
                    url: recorder.InterfaceUrl + '?RecordID=' + recorder.RecordID + '&rpw=' + psw + '&OnlyFlag=1&FlagType=json',
                    success: function (data, textStatus) {
                        if (data && data.Error) {
                            switch (data.Error) {
                                case 1:
                                case 2:
                                case 3:
                                case 4:
                                    recorder.ShowMessageFrame(AudioError[String(data.Error)]);
                                    break;
                                default:
                                    recorder.AudioUrl = recorder.InterfaceUrl + '?RecordID=' + recorder.RecordID + '&rpw=' + psw;
                                    recorder.ShowPlayerFrame();
                                    break;
                            }
                        }
                        else {
                            recorder.AudioUrl = recorder.InterfaceUrl + '?RecordID=' + recorder.RecordID + '&rpw=' + psw;
                            recorder.ShowPlayerFrame();
                        }
                    }
                });
            }
                /*else if (typeof XDomainRequest != "undefined") {
                    //不支持CORS => IE8/IE9
                    //但XDomainRequest 不支持携带Cookie，所以与jsonp没有什么区别
                }*/
            else {
                $.ajax({
                    type: 'get',
                    dataType: 'jsonp',
                    jsonp: 'CALLBACK',
                    url: recorder.InterfaceUrl + '?RecordID=' + recorder.RecordID + '&rpw=' + psw + '&OnlyFlag=1&FlagType=jsonp',
                    success: function (data, textStatus) {
                        if (data && data.Error) {
                            switch (data.Error) {
                                case 1:
                                case 2:
                                case 3:
                                case 4:
                                    recorder.ShowMessageFrame(AudioError[String(data.Error)]);
                                    break;
                                default:
                                    recorder.AudioUrl = recorder.InterfaceUrl + '?RecordID=' + recorder.RecordID + '&rpw=' + psw;
                                    recorder.ShowPlayerFrame();
                                    break;
                            }
                        }
                        else {
                            recorder.AudioUrl = recorder.InterfaceUrl + '?RecordID=' + recorder.RecordID + '&rpw=' + psw;
                            recorder.ShowPlayerFrame();
                        }
                    }
                });
            }
        });
        $(document).unbind('mouseup.dragging');
    };

    //显示提示信息界面
    this.ShowMessageFrame = function (msg) {
        $('#audioplayer').css('display', 'none');
        $('#audiopassword').css('display', 'none');
        $('#audiomessage').css('display', '');

        $('#audiomessagecontent').html(msg);
        $('#btn4message').unbind('click');
        $('#btn4message').bind('click', function () {
            if ($('#audiomessagecontent').text() == AudioError["4"]) {
                recorder.ShowPasswordFrame();
            }
            else {
                recorder.CloseFrame();
            }
        });
        $('#DivDialog').show();
        $(document).unbind('mouseup.dragging');
    };

    //显示播放器界面
    this.ShowPlayerFrame = function () {
        $('#audiomessage').css('display', 'none');
        $('#audiopassword').css('display', 'none');
        $('#audioplayer').css('display', '');

        //process slider
        $("#process").slider();
        $("#processcontroller").css('left', '0%');
        //播放控制
        $('#audiocontroller').unbind('click');
        $('#audiocontroller').bind('click', function () {
            if (recorder.IsPlaying) {
                recorder.Pause();
            }
            else {
                if (recorder.PauseCount > 0) {
                    recorder.Continue();
                }
                else {
                    recorder.Play();
                }
            }
        });
        //$('#processcontroller').slider();
        //播放进度控制
        //        $('#process').unbind('mousedown.dragging');
        //        $('#process').bind('mousedown.dragging', function (e) {
        //            if (!recorder)
        //                return;
        //            recorder.IsDragging = true;
        //            recorder.DraggingStartPoint = { X: e.pageX, Y: e.pageY };

        //            $('#processcontroller').stop(true, false);
        //            recorder.AnimateIsStoped = true;

        //            clearInterval(AudioRecorder.DraggingInterval);
        //            AudioRecorder.DraggingInterval = setInterval(function () {
        //                var TotalTime = $('#audio')[0].duration;
        //                var TotalWidth = parseFloat(String($('#process').css('width')).replace('px', ''));
        //                var CurrentX = parseFloat(String($('#processcontroller').css('left')).replace('px', ''));
        //                var percent = CurrentX / TotalWidth;
        //                var CurrentTime = TotalTime * percent;
        //                $('#audiotime').html(FormatTime(CurrentTime));
        //            }, 100);
        //        });

        $('#processcontroller').unbind('mousedown.dragging');
        $('#processcontroller').bind('mousedown.dragging', function (e) {
            $.Tools.Log('拖拽函数 ==========');
            $.Tools.Log('拖拽函数 开始执行');
            if (!recorder)
                return;
            recorder.IsDragging = true;
            $.Tools.Log('拖拽函数 设置拖拽状态 true');
            recorder.DraggingStartPoint = { X: e.pageX, Y: e.pageY };
            $.Tools.Log('拖拽函数 设置拖拽开始位置 X：' + e.pageX + " Y：" + e.pageY);

            $('#processcontroller').stop(true, false);
            recorder.AnimateIsStoped = true;
            $.Tools.Log('拖拽函数 动画 停止 true');

            clearInterval(AudioRecorder.DraggingInterval);
            $.Tools.Log('拖拽函数 清除拖拽定时器');
            AudioRecorder.DraggingInterval = setInterval(function () {
                $.Tools.Log('拖拽函数 拖拽定时器 ----------');
                var TotalTime = $('#audio')[0].duration;
                var TotalWidth = parseFloat(String($('#process').css('width')).replace('px', ''));
                var CurrentX = parseFloat(String($('#processcontroller').css('left')).replace('px', ''));
                var percent = CurrentX / TotalWidth;
                var CurrentTime = TotalTime * percent;
                $.Tools.Log('拖拽函数 拖拽定时器 拖拽至时间 ' + CurrentTime);
                $('#audiotime').html(FormatTime(CurrentTime));
            }, 100);
        });

        $(document).unbind('mouseup.dragging');
        $(document).bind('mouseup.dragging', function (e) {
            $.Tools.Log('结束拖拽函数 ==========');
            $.Tools.Log('结束拖拽函数 开始执行');
            if (!recorder)
                return;
            clearInterval(AudioRecorder.DraggingInterval);
            $.Tools.Log('结束拖拽函数 清除拖拽定时器');
            recorder.DraggingEndPoint = { X: e.pageX, Y: e.pageY };
            $.Tools.Log('结束拖拽函数 设置拖拽开始位置 X：' + e.pageX + " Y：" + e.pageY);
            recorder.IsDragging = false;
            $.Tools.Log('结束拖拽函数 设置拖拽状态 false');
            var TotalTime = $('#audio')[0].duration;
            var TotalWidth = parseFloat(String($('#process').css('width')).replace('px', ''));
            var CurrentX = parseFloat(String($('#processcontroller').css('left')).replace('px', ''));
            var percent = CurrentX / TotalWidth;
            var CurrentTime = TotalTime * percent;
            $.Tools.Log('结束拖拽函数 拖拽定时器 拖拽至时间 ' + CurrentTime);
            $('#audio')[0].currentTime = CurrentTime;
            recorder.AnimateIsEnded = false;
            $.Tools.Log('结束拖拽函数 动画 停止 false');

            $('#audiocontroller').removeClass('icon_play');
            $('#audiocontroller').addClass('icon_pause');
            $.Tools.Log('结束拖拽函数 开始播放');
            recorder.ProcessTo(percent);
        });


        recorder.Play();
    };

    //时间进度处理程序
    function Process() {
        $.Tools.Log('时间处理函数 ==========');
        $.Tools.Log('时间处理函数 开始执行');
        var audio = $('#audio')[0];
        var ProcessYet = 0;
        var StopFlag = false;
        var timeAll = FormatTime(Duration());
        $.Tools.Log('时间处理函数 TimeAll:' + timeAll);

        clearInterval(AudioRecorder.PlayInterval);
        $.Tools.Log('时间处理函数 清除定时器');

        AudioRecorder.PlayInterval = setInterval(function () {
            $.Tools.Log('时间处理函数 定时器 ----------');
            if (recorder.IsDragging) {
                $.Tools.Log('时间处理函数 定时器 正在拖拽');
                return;
            }
            var ProcessYet = (audio.currentTime / audio.duration) * 100;
            $.Tools.Log('时间处理函数 定时器 百分比 ' + ProcessYet);
            //$('#processcontroller').css("left", ProcessYet + "%");

            $.Tools.Log('时间处理函数 定时器 动画 停止 ' + recorder.AnimateIsStoped);
            $.Tools.Log('时间处理函数 定时器 动画 结束 ' + recorder.AnimateIsEnded);
            if (recorder.AnimateIsStoped && !recorder.AnimateIsEnded) {
                $.Tools.Log('时间处理函数 定时器 动画 停止 未结束');
                if (Duration() != 0) {
                    recorder.AnimateIsStoped = false;
                    $('#processcontroller').animate({ left: '100%' }, (Duration() - audio.currentTime) * 1000, 'linear', function () {
                        $('#processcontroller').stop(true, false);
                        $('#processcontroller').css('left', '0%');
                        recorder.AnimateIsEnded = true;
                        recorder.AnimateIsStoped = true;
                    });
                    $.Tools.Log('时间处理函数 定时器 动画 已启动');
                }
            }
            if (audio.currentTime != recorder.LastCurrentTime) {
                recorder.LastCurrentShowTime = audio.currentTime;
                recorder.LastCurrentTime = audio.currentTime;
                $.Tools.Log('时间处理函数 定时器 播放时间 已重置');
            }
            else {
                recorder.LastCurrentShowTime += 1;
                $.Tools.Log('时间处理函数 定时器 播放时间 ' + recorder.LastCurrentShowTime);
            }
            var currentTime = FormatTime(recorder.LastCurrentShowTime);
            $.Tools.Log('时间处理函数 定时器 播放时间 ' + currentTime);
            if (currentTime != '')
                $('#audiotime').html(currentTime);

            if (StopFlag == true) {
                $.Tools.Log('时间处理函数 定时器 停止标识 true');

                clearInterval(AudioRecorder.PlayInterval);
                AudioRecorder.PlayInterval = null;
                $.Tools.Log('时间处理函数 定时器 清除定时器');

                $('#audiotime').html('00:00');
                $('#audiocontroller').removeClass('icon_pause');
                $('#audiocontroller').addClass('icon_play');
                recorder.Reset();
                $.Tools.Log('时间处理函数 定时器 重置播放状态');

                this.IsPlaying = false;
                this.PauseCount = 0;
                recorder.AnimateIsEnded = true;
                recorder.AnimateIsStoped = true;
            }
            else{
                StopFlag = (currentTime == FormatTime(Duration())) && Duration() != 0;
                $.Tools.Log('时间处理函数 定时器 设置停止标识 ' + StopFlag);
            }

        }, 1000);
    }

    //时间处理，因为时间是以为单位算的，所以这边执行格式处理一下
    function FormatTime(seconds) {
        if (isNaN(seconds))
            return '';
        var minute = parseInt(seconds / 60);
        var second = parseInt(seconds % 60);
        minute = minute >= 10 ? minute : "0" + minute;
        second = second >= 10 ? second : "0" + second;
        return minute + ":" + second;
    }

    //当前歌曲的总时间
    function Duration() {
        var audio = $('#audio')[0];
        if (audio && !isNaN(audio.duration))
            return audio.duration;
        else
            return 0;
    }
};


/***********************  Flash  Player [OLD] **************************/
var isIE = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
var MasterDiv = null;

//configuration
var Configuration = {
    RequiredFlashVersion: {
        MajorVersion: 10,
        MinorVersion: 0,
        Revision: 2
    },
    FlashUrl: {
        'LEFT': window.location.protocol + '//autocall.bitauto.com/PCL/Flash/FlashMp3PlayerV2L.swf?version=2013.1.4',
        'RIGHT': window.location.protocol + '//autocall.bitauto.com/PCL/Flash/FlashMp3PlayerV2R.swf?version=2013.1.4'
    }
};

//get current flash version
function FlashVersion() {
    var version;
    var axo;
    var e;
    // NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry
    try {
        // version will be set for 7.X or greater players
        axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
        version = axo.GetVariable("$version");
    } catch (e) {
    }
    if (!version) {
        try {
            axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
            version = "WIN 6,0,21,0";
            axo.AllowScriptAccess = "always";
            version = axo.GetVariable("$version");
        } catch (e) {
        }
    }
    if (!version) {
        try {
            // version will be set for 4.X or 5.X player
            axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
            version = axo.GetVariable("$version");
        } catch (e) {
        }
    }
    if (!version) {
        try {
            // version will be set for 3.X player
            axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
            version = "WIN 3,0,18,0";
        } catch (e) {
        }
    }
    if (!version) {
        try {
            // version will be set for 2.X player
            axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
            version = "WIN 2,0,0,11";
        } catch (e) {
            version = -1;
        }
    }
    return version;
}
function GetFlashVersion() {
    // NS/Opera version >= 3 check for Flash plugin in plugin array
    var flashVer = -1;

    if (navigator.plugins != null && navigator.plugins.length > 0) {
        if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
            var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
            var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
            var descArray = flashDescription.split(" ");
            var tempArrayMajor = descArray[2].split(".");
            var versionMajor = tempArrayMajor[0];
            var versionMinor = tempArrayMajor[1];
            var versionRevision = descArray[3];
            if (versionRevision == "") {
                versionRevision = descArray[4];
            }
            if (versionRevision[0] == "d") {
                versionRevision = versionRevision.substring(1);
            } else if (versionRevision[0] == "r") {
                versionRevision = versionRevision.substring(1);
                if (versionRevision.indexOf("d") > 0) {
                    versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
                }
            }
            var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
        }
    }
        // MSN/WebTV 2.6 supports Flash 4
    else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
        // WebTV 2.5 supports Flash 3
    else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
        // older WebTV supports Flash 2
    else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
    else if (isIE && isWin && !isOpera) {
        flashVer = FlashVersion();
    }
    return flashVer;
}
//check current flash version
function DetectFlashVersion() {
    versionStr = GetFlashVersion();
    if (versionStr == -1) {
        return false;
    } else if (versionStr != 0) {
        if (isIE && isWin && !isOpera) {
            // Given "WIN 2,0,0,11"
            tempArray = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
            tempString = tempArray[1];			// "2,0,0,11"
            versionArray = tempString.split(",");	// ['2', '0', '0', '11']
        } else {
            versionArray = versionStr.split(".");
        }
        var versionMajor = versionArray[0];
        var versionMinor = versionArray[1];
        var versionRevision = versionArray[2];
        // is the major.revision >= requested major.revision AND the minor version >= requested minor
        if (versionMajor > parseFloat(Configuration.RequiredFlashVersion.MajorVersion)) {
            return true;
        } else if (versionMajor == parseFloat(Configuration.RequiredFlashVersion.MajorVersion)) {
            if (versionMinor > parseFloat(Configuration.RequiredFlashVersion.MinorVersion))
                return true;
            else if (versionMinor == parseFloat(Configuration.RequiredFlashVersion.MinorVersion)) {
                if (versionRevision >= parseFloat(Configuration.RequiredFlashVersion.Revision))
                    return true;
            }
        }
        return false;
    }
}

//element absolute position { x: 0, y: 0 }
function ElementAbsolutePosition(Object) {
    var x = y = 0;
    do {
        x += Object.offsetLeft || 0;
        y += Object.offsetTop || 0;
        Object = Object.offsetParent;
    }
    while (Object && Object != MasterDiv);
    return { 'x': x, 'y': y };
}

//get flash player html
function GetFlashHtml(RecordID, Position, InterfaceID) {
    var rid = encodeURIComponent(encodeURIComponent(RecordID));
    var hasRightVersion = DetectFlashVersion();
    var CurrentInterface = InterfaceUrl[String(InterfaceID)];
    var FlashUrl = Position == '0' ? Configuration.FlashUrl.RIGHT : Configuration.FlashUrl.LEFT;
    var html = '';
    if (hasRightVersion) {
        html = '\
        <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="' + window.location.protocol + '//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0" width="191" height="80" id="FlashMp3Player" name="FlashMp3Player" align="middle" >\
            <param name="allowScriptAccess" value="always" />\
            <param name="allowFullScreen" value="false" />\
            <param name="movie" value="' + FlashUrl + '" />\
            <param name="quality" value="high" />\
            <param name="menu" value="false">\
            <param name="flashvars" value="RecordID=' + rid + '&DealerID=0&InterfaceUrl=' + CurrentInterface + '&DownloadUrl=' + CurrentInterface + '">\
            <embed flashvars="RecordID=' + rid + '&DealerID=0&InterfaceUrl=' + CurrentInterface + '&DownloadUrl=' + CurrentInterface + '" src="' + FlashUrl + '" quality="high" menu ="false" width="191" height="80" name="Mp3Player" align="middle" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer_cn" />\
        </object>';

    }
    else {
        html = '\
        <div style="background-image: url(Images/Icon/FlashMp3PlayerBg.png);width:191px;height:80px">\
            <div style="font-size: 12px; color: #ffffff;padding:10px;">你的FlashPlayer版本过低，无法正常收听录音，请点击下面链接升级后收听。</div>\
            <div style="font-size: 12px; text-align: center">\
                <a href="http://www.adobe.com/go/getflashplayer/">获取FlashPlayer</a>\
            </div>\
        </div>';
    }
    return html;
}

//download record file in current page
function RecordDownload(RecordID) {
    window.location = requestUrl + "?RecordID=" + encodeURIComponent(RecordID);
}

/***********************  Page Logic  **************************/
$(function () {
    //显示
    $('.player-trigger').click(function () {
        ShowPlayer($(this));
    });
    $(document).ready(function () {
        if ($('#DivDialog')[0])
            document.body.appendChild(document.getElementById('DivDialog'));
        else {
            var div = document.createElement("div");
            div.setAttribute('style', 'z-index: 1001;position: absolute; width: 191px;height: 80px;display: none;');
            div.setAttribute('id', 'DivDialog');
            document.body.appendChild(div);
        }
        if (BroswerSupportAudio) {
            $('#DivDialog').addClass('popup_layout');
        }
        else {
            $('#DivDialog').css('width', '191px');
            $('#DivDialog').css('height', '80px');
        }
    });
});

function ShowPlayer(obj) {
    var CurrentTrigger = $(obj);
    var InterfaceID = CurrentTrigger.attr('InterfaceID') || '1';
    var RecordID = CurrentTrigger.attr('RecordID') || '';
    var ShowPosition = CurrentTrigger.attr('Position') || '0';
    var AutoClick2Hide = !(CurrentTrigger.attr('AutoClick2Hide') == undefined);
    var OnlyHtml5 = false;
    if (BroswerSupportAudio) {
        var Version = CurrentTrigger.attr('Version') || '';
        Version = String(Version).toLowerCase();
        if (Version == "flash") {
            BroswerSupportAudio = false;
        }
        else if (Version == "html5") {
            BroswerSupportAudio = true;
        }
        else if (Version == "onlyhtml5") {
            OnlyHtml5 = true;
        }
    } else {
        var Version = CurrentTrigger.attr('Version') || '';
        Version = String(Version).toLowerCase(); 
        if (Version == "onlyhtml5") {
            OnlyHtml5 = true;
        }
    }

    //如果trigger没有id，则指定一个
    $('#CurrentAudioTrigger').removeAttr('id');
    if (CurrentTrigger.attr('id') == undefined) {
        CurrentTrigger.attr('id', 'CurrentAudioTrigger');
    }

    //如果弹层当前没有显示，为了防止显示之后马上被autoclick2hide事件关闭掉，则首先移除autoclick2hide事件的绑定
    if ($('#DivDialog').css('display') == 'none')
        $(document).unbind(".autoclick2hide");

    if (BroswerSupportAudio) {
        if ($('*[clicked="clicked"]').length == 1 && $('*[clicked="clicked"]').attr('id') == CurrentTrigger.attr('id')) {
            return;
        }
        CurrentTrigger.attr('clicked', 'clicked');

        var targetDiv = '#DivDialog';
        var Interface = InterfaceUrl[String(InterfaceID)];
        var targetDivOH = $(targetDiv).outerHeight(), targetDivWidth = $(targetDiv).width();
        var targetDivH = $(targetDiv).height(), eleWidth = CurrentTrigger.width(), self = CurrentTrigger;
        var offestLeft = CurrentTrigger.offset().left, offsetTop = CurrentTrigger.offset().top;
        targetDivH = 112;/*display:none;时获取不到高度，设置为固定值*/
        if ((offsetTop + targetDivOH) > $(window).height()) {
            $(targetDiv).show().addClass('arrow_down').css({ 'position': 'absolute', 'left': offestLeft - targetDivWidth / 2 + eleWidth / 2, 'top': offsetTop - targetDivH });
        } else {
            $(targetDiv).show().removeClass('arrow_down').css({ 'position': 'absolute', 'left': offestLeft - targetDivWidth / 2 + eleWidth / 2, 'top': offsetTop + 20 });
        };

        recorder = new AudioRecorder({ RecordID: RecordID, InterfaceID: InterfaceID, AutoClick2Hide: AutoClick2Hide });
        recorder.ShowFrame();

        //窗体变化 重新计算弹层位置 
        $(window).resize(function () {
            var offestLeft = self.offset().left, offsetTop = self.offset().top;
            if ((offsetTop + targetDivOH) > $(window).height()) {
                $(targetDiv).addClass('arrow_down').css({ 'position': 'absolute', 'left': offestLeft - targetDivWidth / 2 + eleWidth / 2, 'top': offsetTop - targetDivH });;
            } else {
                $(targetDiv).removeClass('arrow_down').css({ 'position': 'absolute', 'left': offestLeft - targetDivWidth / 2 + eleWidth / 2, 'top': offsetTop + 20 });
            };
        });
        //event.stopPropagation();
    }
    else {
        if (OnlyHtml5) {
            if ($('*[clicked="clicked"]').length == 1 && $('*[clicked="clicked"]').attr('id') == CurrentTrigger.attr('id')) {
                return;
            }
            CurrentTrigger.attr('clicked', 'clicked');

            var targetDiv = '#DivDialog';
            var Interface = InterfaceUrl[String(InterfaceID)];
            var targetDivOH = $(targetDiv).outerHeight(), targetDivWidth = $(targetDiv).width();
            var targetDivH = $(targetDiv).height(), eleWidth = CurrentTrigger.width(), self = CurrentTrigger;
            var offestLeft = CurrentTrigger.offset().left, offsetTop = CurrentTrigger.offset().top;
            targetDivH = 112; /*display:none;时获取不到高度，设置为固定值*/
            if ((offsetTop + targetDivOH) > $(window).height()) {
                $(targetDiv).show().addClass('arrow_down').css({ 'position': 'absolute', 'left': offestLeft - targetDivWidth / 2 + eleWidth / 2, 'top': offsetTop - targetDivH });
            } else {
                $(targetDiv).show().removeClass('arrow_down').css({ 'position': 'absolute', 'left': offestLeft - targetDivWidth / 2 + eleWidth / 2, 'top': offsetTop + 20 });
            };
            recorder = new AudioRecorder({ RecordID: RecordID, InterfaceID: InterfaceID, AutoClick2Hide: AutoClick2Hide });

            recorder.ShowMessageFrame('此设备暂不支持播放录音');
            
            //窗体变化 重新计算弹层位置 
            $(window).resize(function () {
                var offestLeft = self.offset().left, offsetTop = self.offset().top;
                if ((offsetTop + targetDivOH) > $(window).height()) {
                    $(targetDiv).addClass('arrow_down').css({ 'position': 'absolute', 'left': offestLeft - targetDivWidth / 2 + eleWidth / 2, 'top': offsetTop - targetDivH }); ;
                } else {
                    $(targetDiv).removeClass('arrow_down').css({ 'position': 'absolute', 'left': offestLeft - targetDivWidth / 2 + eleWidth / 2, 'top': offsetTop + 20 });
                };
            });
        }
        else {
            var content = GetFlashHtml(RecordID, ShowPosition, InterfaceID);
            document.getElementById('DivDialog').innerHTML = '';
            $('#DivDialog').append(content);
            $('#DivDialog').attr('class', '');
            document.getElementById('DivDialog').style.display = 'block';
            document.getElementById('DivDialog').style.position = 'absolute';
            if (String(ShowPosition) == '0') {
                document.getElementById('DivDialog').style.left = (ElementAbsolutePosition(CurrentTrigger[0])['x'] - 200/*Flash宽度*/) + "px";
                document.getElementById('DivDialog').style.top = (ElementAbsolutePosition(CurrentTrigger[0])['y'] - document.getElementById('DivDialog').offsetHeight / 2 + CurrentTrigger[0].offsetHeight / 2) + "px";
            }
            else {
                document.getElementById('DivDialog').style.left = (ElementAbsolutePosition(CurrentTrigger[0])['x'] + CurrentTrigger[0].offsetWidth) + "px";
                document.getElementById('DivDialog').style.top = (ElementAbsolutePosition(CurrentTrigger[0])['y'] - document.getElementById('DivDialog').offsetHeight / 2 + CurrentTrigger[0].offsetHeight / 2) + "px";
            }
        }
    }

    $('*[clicked="clicked"]').each(function () {
        if ($(this).attr('id') != CurrentTrigger.attr('id'))
            $(this).removeAttr('clicked');
    });

    //绑定autoclick2hide事件
    if (AutoClick2Hide) {
        $(document).bind("click.autoclick2hide", function (event) {
            if (BroswerSupportAudio) {
                if (recorder && recorder != null) {
                    if ($(event.target).attr('RecordID') && $(event.target).attr('InterfaceID') && $(event.target).attr('id') != $(CurrentTrigger).attr('id')) {
                        recorder.CloseFrame();
                        $(event.target).click();
                    }
                    else if ($(event.target).attr('id') != $(CurrentTrigger).attr('id') && $(event.target).parents('#DivDialog').length <= 0 && $(event.target).parents('#' + $(CurrentTrigger).attr('id')).length <= 0) {
                        recorder.CloseFrame();
                    }
                }
            }
            else {
                if ($(event.target).attr('id') != $(CurrentTrigger).attr('id') && $(event.target).parents('#DivDialog').length <= 0 && $(event.target).parents('#' + $(CurrentTrigger).attr('id')).length <= 0) {
                    $('#DivDialog').css('display', 'none');
                    $('#DivDialog').html('');
                }
            }
        });
    }
}





(function ($) {

    $.Tools = function () {
    };

    //将json对象转换为json格式的字符串
    $.Tools.FormatJson = function (obj) {
        switch (typeof (obj)) {
            case 'object':
                var ret = [];
                if (obj == null) {
                    return '{' + ret.join(',') + '}';
                }
                else if (obj instanceof Array) {
                    for (var i = 0, len = obj.length; i < len; i++) {
                        ret.push(FormatJson(obj[i]));
                    }
                    return '[' + ret.join(',') + ']';
                }
                else if (obj instanceof RegExp) {
                    return obj.toString();
                }
                else {
                    for (var a in obj) {
                        ret.push('"' + a + '":' + $.Tools.FormatJson(obj[a]));
                    }
                    return '{' + ret.join(',') + '}';
                }
            case 'function':
                return 'function() {}';
            case 'number':
                return obj.toString();
            case 'string':
                return "\"" + obj.replace(/(\\|\")/g, "\\$1").replace(/\n|\r|\t/g, function (a) { return ("\n" == a) ? "\\n" : ("\r" == a) ? "\\r" : ("\t" == a) ? "\\t" : ""; }) + "\"";
            case 'boolean':
                return obj.toString();
            default:
                return undefined;
        }
    };
    //输出当前时间 yyyy-MM-dd HH:mm:ss
    $.Tools.TimeNow = function () {
        var datetime = new Date();
        var year = datetime.getFullYear();
        var month = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
        var date = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
        var hour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours();
        var minute = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
        var second = datetime.getSeconds() < 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
        return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
    };
    //日志输出
    $.Tools.Log = function (logcontent) {
        try {
            console.log($.Tools.TimeNow() + "  " + logcontent);
        }
        catch (e) {
        }
    };
    $.Tools.IsPCBrowser = function(){    
        var userAgentInfo = navigator.userAgent;  
        var Agents = new Array("Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod");    
        var flag = true;    
        for (var v = 0; v < Agents.length; v++) {    
            if (userAgentInfo.indexOf(Agents[v]) > 0) { flag = false; break; }    
        }    
        return flag;    
    }  
})(jQuery);